package com.uwantsoft.business.service.domain.park.search.statusupdator;

import com.uwantsoft.business.service.domain.park.search.SearchedPark;
import com.uwantsoft.business.service.domain.park.search.guard.ParkingRequestSender;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Zhang Hui on 2015/5/12.
 */
public class GuardConfirmationParkStatusUpdator implements ParkStatusUpdator {

    private List<SearchedPark> parks = new ArrayList<SearchedPark>();

    private List<SearchedPark> needConfirmParks = new ArrayList<SearchedPark>();

    protected ParkingRequestSender parkingRequestSender = new ParkingRequestSender();


    public GuardConfirmationParkStatusUpdator(List<SearchedPark> parks) {
        this.parks = parks;
        initialNeedConfirmParks();
    }

    private void initialNeedConfirmParks() {
        Iterator<SearchedPark> parkIterator = parks.iterator();
        while (parkIterator.hasNext()) {
            SearchedPark park = parkIterator.next();
            if (park.status() == null) {
                needConfirmParks.add(park);
                parkIterator.remove();
            }
        }
    }

    @Override
    public void update() {
        parkingRequestSender.send(needConfirmParks);
        cycleCheckGuardResponse();
    }

    private void cycleCheckGuardResponse() {

        final List<String> needConfirmParkGuids = new ArrayList<String>();
        for (SearchedPark needConfirmPark : needConfirmParks) {
            needConfirmParkGuids.add(needConfirmPark.getGuid());
        }

        final ParksStatusResolver parksStatusResolver = new ParksStatusResolver();
        final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);

        scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                ParksStatusResolverResult statusResolverResult = parksStatusResolver.resolve(needConfirmParkGuids);

                if (statusResolverResult.done()) {
                    parks.addAll(statusResolverResult.parks());
                    scheduledThreadPoolExecutor.shutdown();
                }
            }
        }, 0, 5, TimeUnit.SECONDS);

    }


}
